<?php

include "../inc/inc.koneksi.php";
include "../inc/logging.php";

$strQuery = '';
$strQuery .= ' SELECT A.nama_tahunajaran AS ta, B.pilihansekolah AS sekolah, COUNT(B.noinduk) AS jumlah';
$strQuery .= ' FROM tahunajaran A ';
$strQuery .= ' LEFT OUTER JOIN siswa B ON B.id_tahunajaran = A.id_tahunajaran ';

if (isset($_POST['ta'])) {
    $ta = $_POST['ta'];
    if ($ta != '') {
        $strQuery .= ' WHERE A.id_tahunajaran = ' . $ta;
    }
}

$strQuery .= ' GROUP BY A.id_tahunajaran, B.pilihansekolah ';

note('Query: ' . $strQuery);

$query = mysql_query($strQuery);
$categories = array();

$numTk = array();
$numPaud = array();

$currentTa = '';
$rows = mysql_num_rows($query);
$i = 0;
while ($result = mysql_fetch_array($query)) {

    $resultTa = trim($result['ta']);
    $resultSekolah = trim($result['sekolah']);
    $resultJumlah = $result['jumlah'];

    note('TA: ' . $resultTa);
    note('Sekolah: ' . $resultSekolah);
    note('Jumlah: ' . $resultJumlah);

    // meletakan macam-macam untuk chart
    if ($currentTa == '') {
        $currentTa = $resultTa;
        array_push($categories, $resultTa);

        if ($resultSekolah == 'TK') {
            array_push($numTk, (int) $resultJumlah);
        } else if ($resultSekolah == 'PAUD') {
            array_push($numPaud, (int) $resultJumlah);
        } else {
            array_push($numTk, (int) 0);
            array_push($numPaud, (int) 0);
        }
    } else {
        note('$resultTa == $currentTa : ' . ($resultTa == $currentTa));

        if ($resultTa == $currentTa) {

            if ($resultSekolah == 'TK') {
                array_push($numTk, (int) $resultJumlah);
            } else if ($resultSekolah == 'PAUD') {
                array_push($numPaud, (int) $resultJumlah);
            }
        } else {

            array_push($categories, $resultTa);
            $currentTa = $resultTa;

            if ($resultSekolah == 'TK') {
                array_push($numTk, (int) $resultJumlah);
            } else if ($resultSekolah == 'PAUD') {
                array_push($numPaud, (int) $resultJumlah);
            } else {
                array_push($numTk, (int) $resultJumlah);
                array_push($numPaud, (int) $resultJumlah);
            }
        }
    }

    $i++;
}

$seriesTk = array(
    'name' => 'TK',
    'data' => $numTk
);

$seriesPaud = array(
    'name' => 'PAUD',
    'data' => $numPaud
);

$series = array();
array_push($series, $seriesTk);
array_push($series, $seriesPaud);

$return = array(
    'query' => $strQuery,
    'categories' => $categories,
    'series' => $series
);

echo json_encode($return);
?>